package com.sxg.service.impl;

import com.sxg.constant.Constants;
import com.sxg.service.SxgFileService;
import com.sxg.utils.ImageCompressionUtils;
import com.sxg.utils.code.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

@Service
@Slf4j
public class SxgFileServiceImpl implements SxgFileService {

    @Value("${sxg.profile}")
    private String filePath;

    @Value("${server.port}")
    private String port;


    @Override
    public AjaxResult upload(MultipartFile file) {
        //校验文件
        if (Objects.isNull(file) || file.isEmpty()) {
            return AjaxResult.error("文件不能为空");
        }

        //判断是否为图片
        if (!ImageCompressionUtils.isImage(file.getOriginalFilename())) {
            return AjaxResult.error("不支持的图片格式");
        }

        return AjaxResult.success().put("fileUrl", uploadFile(file));
    }

    @Override
    public String uploadFile(MultipartFile file) {
        // 文件上传的具体实现
        try {
            String filename = file.getOriginalFilename();
            String newFileName = "sxg" + "_" + System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
            boolean isGif = ".gif".equals(filename.substring(filename.lastIndexOf(".")));

            //图片超过650kb压缩文件后保存
            if (file.getSize() > 650000 && !isGif) {
                InputStream inputStream = file.getInputStream();
                Thumbnails.of(inputStream)
                        .scale(1)
                        .outputQuality(0.25f)
                        .toFile(filePath + "/" + newFileName);
            } else if (file.getSize() > 650000 && isGif) {
                ImageCompressionUtils.compressImage(filePath + "/" + newFileName, file);
            } else {
                file.transferTo(new File(filePath + "/" + newFileName));
            }


            return "http://" + "47.115.220.79" + ":" + port + Constants.RESOURCE_PREFIX + "/" + newFileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
